//
//  HomeViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "HomeViewController.h"
#import "PPUpdateViewController.h"
#import "GoodDetailViewController.h"
#import "MessageCenterViewController.h"

#import "HomeSubscriptButton.h"
#import "ProductCollectionViewCell.h"
#import "HomeTableReusableView.h"

#import "HomeHeadModel.h"
#import "HomeProductItemModel.h"

#import "OYCountDownManager.h"

NSString *const k_homeProductItemSource = @"k_homeProductItemSource";
@interface HomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource> {
    
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
}

@property (nonatomic, strong) HomeTableReusableView *homeHeadView;
@property (nonatomic, strong) HomeHeadModel         *headModel;

@property (nonatomic ,strong) UICollectionView *homeCollectionView;
@property (nonatomic, strong) NSMutableArray<HomeProductItemModel *>*productListArray;

@property (nonatomic, assign) CGFloat mainIconItemHeight;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) HomeSubscriptButton *messageItem;
@end

@implementation HomeViewController

- (void)dealloc {
    [kCountDownManager removeSourceWithIdentifier:k_homeProductItemSource];
    [kCountDownManager invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self request_HomeData];

    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
//    [self refreshUnReadMsgCount];
    [kCountDownManager start];
    [kCountDownManager addSourceWithIdentifier:k_homeProductItemSource];
}

#pragma mark 首页发生刷新行为时，reload定时器
- (void)reloadTime {
    [kCountDownManager reloadSourceWithIdentifier:k_homeProductItemSource];
}


//#pragma mark 刷新未读消息数
//- (void)refreshUnReadMsgCount {
//
//    [self.messageItem setCountNum:0];
//}

- (void)request_HomeData {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@"1" forKey:@"curPage"];
    [dic setValue:@"20" forKey:@"pageSize"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_HOME_ALL];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    self.headModel = [[HomeHeadModel alloc] init];
                    
                    self.headModel.bannerModel = [[HomeHeadListModel alloc] init];
                    self.headModel.notiMsgModel = [[HomeHeadListModel alloc] init];
                    self.headModel.mainIconModel = [[HomeHeadListModel alloc] init];
                    
                    //banner
                    self.headModel.bannerModel.itemArray = @[].mutableCopy;
                    NSArray *bannerArray = [resultDic valueForKey:@"bannerRes"];
                    for (int i = 0; i<bannerArray.count; i++) {
                        
                        NSDictionary *bannerDic = [bannerArray objectAtIndex:i];
                        HomeHeadItemModel *model = [[HomeHeadItemModel alloc] init];
                        model.itemActionModel = [[PP_jumpModel alloc] init];
                        
                        model.itemActionModel.type = CommentClickType_HtmlPage;
                        model.itemActionModel.ID = @"www.baidu.com";
                        model.itemImagePath = [bannerDic valueForKey:@"imagePath"];
                        
                        [self.headModel.bannerModel.itemArray addObject:model];
                    }
                    
                    //icon
                    self.headModel.mainIconModel.itemArray = @[].mutableCopy;
                    NSArray *mainIconArray = [resultDic valueForKey:@"sysDocRes"];

                    for (int i = 0; i < mainIconArray.count; i++) {
                        
                        NSDictionary *mainIconDic = [mainIconArray objectAtIndex:i];
                        HomeHeadItemModel *model = [[HomeHeadItemModel alloc] init];
                        model.itemActionModel = [[PP_jumpModel alloc] init];
//                        model.itemActionModel.type = CommentClickType_HtmlPage;
                        model.itemActionModel.ID = [mainIconDic valueForKey:@"id"];
                        model.itemImagePath = [mainIconDic valueForKey:@"imagePath"];
                        model.itemTitle = [mainIconDic valueForKey:@"title"];
                        [self.headModel.mainIconModel.itemArray addObject:model];
                    }
                    //计算mainicon区域的高度
                    NSInteger lineCount  = self.headModel.mainIconModel.itemArray.count/4 + (self.headModel.mainIconModel.itemArray.count%4>0?1:0);
                    self.mainIconItemHeight = lineCount * homeMainIconHeight;
                    
                    //product
                    self.productListArray = @[].mutableCopy;
                    NSArray *productArray = [resultDic valueForKey:@"auctionInfoRes"];
                    
                    if ([productArray isKindOfClass:[NSArray class]]) {
                        for (int i = 0; i < productArray.count; i++) {
                            NSDictionary *productDic = [productArray objectAtIndex:i];
                            HomeProductItemModel *productModel = [[HomeProductItemModel alloc] init];
                            productModel.productID = [productDic valueForKey:@"id"];
                            productModel.productName = [productDic valueForKey:@"goodsName"];
                            productModel.productImage = [productDic valueForKey:@"coverImgPath"];
                            
                            productModel.auctionPrice = [productDic valueForKey:@"goodsStartingPrice"];
                            productModel.marketPrice = [productDic valueForKey:@"goodsMarketPrice"];
                            
                            productModel.beginTimestamp = [[productDic valueForKey:@"startTime"] doubleValue];
                            productModel.endTimestamp = [[productDic valueForKey:@"endTime"] doubleValue];//2019-08-02
                            
                            productModel.countDownSource = k_homeProductItemSource;
                            [self.productListArray addObject:productModel];
                        }
                    }
                }

            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
            
            [self.homeCollectionView reloadData];

        } else {
            
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
            [SVProgressHUD dismissWithDelay:1];
        }

        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        [self.homeCollectionView.mj_header endRefreshing];

    } FailedBlock:^(NSError * _Nonnull error) {
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_HomeData];
        }];
    }];
}

#pragma mark 初始化view
- (void)initView {
    
    self.title = @"拍拍得利";
    self.view.backgroundColor = [UIColor brownColor];

    CGFloat width = self.view.frame.size.width;
    self.mainIconItemHeight = homeMainIconHeight;
    
//    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.messageItem];
//    self.navigationItem.rightBarButtonItem = rightItem;
    
    CGFloat cellWidth;
    cellWidth = width - 2 * PP_Global_Collection_Distance;
    _cellSize =  CGSizeMake(cellWidth, cellWidth/4 +16);
    _collectionEdge = UIEdgeInsetsMake(PP_Global_Collection_Distance, PP_Global_Collection_Distance, PP_Global_Collection_Distance, PP_Global_Collection_Distance);

    [self.view addSubview:self.homeCollectionView];
    [self.homeCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
}

#pragma mark 去消息中心
- (void)goMsgCenter {
    [self.navigationController pushViewController:[MessageCenterViewController new] animated:YES];
}

#pragma mark collectionDelegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.productListArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {

    self.homeHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeTableReusableView" forIndexPath:indexPath];
    [self.homeHeadView fillHeaderWith:self.headModel];

    self.homeHeadView.headerActionHandleBlock = ^(PP_jumpModel * _Nonnull model) {
        [[TTJumpManager share] pushViewControllerWithModel:model];
    };
    return self.homeHeadView;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ProductCollectionViewCell *cell;
    if (!cell) {
       cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductCollectionViewCell" forIndexPath:indexPath];
    }
//    cell.model = self.productListArray[indexPath.row];
    [cell fillCellWithModel:self.productListArray[indexPath.row]];
    WEAKSELF
    cell.countDownZero = ^(HomeProductItemModel * _Nonnull model) {
        if (indexPath.row < weakSelf.productListArray.count) {
            [weakSelf.productListArray replaceObjectAtIndex:indexPath.row withObject:model];//复用的时候永用到
        }
    };
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return _cellSize;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section {
    return _collectionEdge;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
    detailVC.goodsID = self.productListArray[indexPath.row].productID;
    detailVC.type = PPPaiingGoodsDetail;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    return  CGSizeMake(TTScreenWidth, PP_Home_Banner_Scale * TTScreenWidth + PP_Home_MsgNoti_ItemHeight + self.mainIconItemHeight + homeNormalImageHeight +10);
}

//- (HomeSubscriptButton *)messageItem {
//    if (!_messageItem) {
//        _messageItem = [[HomeSubscriptButton alloc] initWithSize:CGSizeMake(40, 40)];
//        [_messageItem.topButton setImage:[UIImage imageNamed:@"homeMsg"] forState:UIControlStateNormal];;
//        _messageItem.userInteractionEnabled = YES;
//        [_messageItem.topButton addTarget:self action:@selector(goMsgCenter) forControlEvents:UIControlEventTouchUpInside];
//    }
//    return _messageItem;
//}

- (UICollectionView *)homeCollectionView {
    if (!_homeCollectionView) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.headerReferenceSize = CGSizeMake(TTScreenWidth, TTScreenWidth * PP_Home_Banner_Scale + PP_Home_MsgNoti_ItemHeight + self.mainIconItemHeight + homeNormalImageHeight +10);

        _homeCollectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        _homeCollectionView.delegate = self;
        _homeCollectionView.dataSource = self;
        
        _homeCollectionView.showsVerticalScrollIndicator = NO;
        _homeCollectionView.showsHorizontalScrollIndicator = NO;
        
        _homeCollectionView.backgroundColor = [UIColor whiteColor];
        [_homeCollectionView registerNib:[UINib nibWithNibName:@"ProductCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ProductCollectionViewCell"];
        [_homeCollectionView registerClass:[HomeTableReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeTableReusableView"];
        
        WEAKSELF
        _homeCollectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf request_HomeData];
            [weakSelf reloadTime];
        }];
    }
    return _homeCollectionView;
}

@end
